<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>个人中心</title>
    <link rel="stylesheet" href="common/css/all.min.css">
    <link href="plugs/layui/css/layui.css" rel="stylesheet"/>
    <link href="common/css/user.css" rel="stylesheet"/>
</head>
<body>
<!-- 顶部导航 -->
<div class="header" th:include="include :: header">
<!--    <button class="back-btn"><i class="fas fa-arrow-left"></i> 返回</button>-->
<!--    <div class="title">个人中心</div>-->
<!--    <button class="exit-btn">退出 <i class="fas fa-sign-out-alt"></i></button>-->
</div>

<!-- 内容区域 -->
<div class="content">
    <!-- 个人资料区域 -->
    <div class="profile-section">
        <div class="avatar-container" id="avatar-container">
            <!-- 如果有头像图片，使用下面的img标签 -->
            <img id="avatar-image" src="" alt="用户头像" class="avatar" style="display: none;">
            <!-- 如果没有头像图片，使用占位图标 -->
            <div class="avatar-placeholder" id="avatar-placeholder">
                <i class="fas fa-user"></i>
            </div>
        </div>
        <input type="file" id="avatar-upload" accept="image/*">
        <div class="user-name">张小明</div>
<!--        <div class="user-title">高级项目经理</div>-->
    </div>

    <!-- 纵向菜单按钮区域 -->
    <div class="menu-section">
        <button class="menu-button" onclick="modifyPassword()">
            <div class="menu-icon password-icon">
                <i class="fas fa-key"></i>
            </div>
            <div class="menu-text">修改密码</div>
            <div class="menu-arrow">
                <i class="fas fa-chevron-right"></i>
            </div>
        </button>

        <button class="menu-button" onclick="addBirthday()">
            <div class="menu-icon birthday-icon">
                <i class="fas fa-birthday-cake"></i>
            </div>
            <div class="menu-text">添加生日</div>
            <div class="menu-arrow">
                <i class="fas fa-chevron-right"></i>
            </div>
        </button>

        <button class="menu-button" onclick="showDlt()">
            <div class="menu-icon lottery-icon">
                <i class="fas fa-ticket-alt"></i>
            </div>
            <div class="menu-text">大乐透</div>
            <div class="menu-arrow">
                <i class="fas fa-chevron-right"></i>
            </div>
        </button>
    </div>
</div>

<!-- 底部导航 -->
<div class="footer" th:include="include :: footer('user')"></div>

<form action="" class="layui-form" style="display: none" lay-filter="add-form" id="add-form">
    <div class="layui-form-item">
        <input type="text" name="remark" id="remark" placeholder="备注" autocomplete="off" class="layui-input">
    </div>
    <div class="layui-form-item">
        <input type="checkbox" name="type" id="type" value="1" checked lay-skin="switch" lay-filter="switchType" title="农历|新历">
    </div>
    <div class="layui-form-item">
        <input type="text" name="birthday" readonly class="layui-input" id="birthday" placeholder="yyyy-MM-dd">
    </div>
</form>

<script src="common/js/jquery.min.js"></script>
<script src="plugs/layui/layui.js"></script>
<script src="common/js/common.js"></script>

<script>
    $(function () {
        let user = sessionStorage.getItem("currentUser");
        if (user){
            let photo = JSON.parse(user).photo;
            if (photo !== '' && photo !== undefined && photo !== null){
                $("#avatar-container").html('<img id="avatar-image" src="'+photo+'" alt="用户头像" class="avatar">');
                // $("#avatar-image").attr("src", photo);
            }
            $(".user-name").html(JSON.parse(user).name);
        }

        //
        // $("#avatar-upload").on("change", function () {
        //     let file = document.getElementById("file").files[0];
        //     let formData = new FormData();
        //     formData.append("file", file);
        //     let p = file.name;
        //     if (!p.toLowerCase().endsWith("png") && !p.toLowerCase().endsWith("jpg")){
        //         layer.msg("请选择图片作为头像", {icon: 2});
        //         $("#file").val('');
        //         return false;
        //     }
        //     $.ajax({
        //         type: 'post',
        //         url: "/api/savePhoto",
        //         data: formData,
        //         cache: false,
        //         processData: false,
        //         contentType: false,
        //     }).success(function (result) {
        //         $("#photo").attr("src", result.data.photo);
        //         sessionStorage.setItem("currentUser", JSON.stringify(result.data));
        //     }).error(function () {
        //         layer.msg("头像修改失败", {icon: 2});
        //     });
        // })
    })

    /**
     * 修改密码
     */
    function modifyPassword() {
        layer.open({
            closeBtn: 1,
            type: 1,
            title:'修改密码',
            btn:['保存', '关闭'],
            area: ['80%', '500'],
            btnAlign: 'c',
            content: '' +
                '<form class="layui-form">\n' +
                '  <div class="layui-form-item">\n' +
                // '    <label class="layui-form-label"><font color="red">*</font>密码</label>\n' +
                // '    <div class="layui-input-block">\n' +
                '      <input type="password" name="password" id="password" placeholder="请输入密码" autocomplete="off" class="layui-input">\n' +
                // '    </div>\n' +
                '  </div>' +
                '  <div class="layui-form-item">\n' +
                // '    <label class="layui-form-label"><font color="red">*</font>确认</label>\n' +
                // '    <div class="layui-input-block">\n' +
                '      <input type="password" name="pwd" id="pwd" placeholder="请输入确认密码" autocomplete="off" class="layui-input">\n' +
                // '    </div>\n' +
                '  </div>' +
                '</form>',
            yes: function () {
                savePassword();
            },
            btn2: function (index) {
                layer.close(index);
            }
        })
    }

    /**
     * 保存密码
     * @returns {boolean}
     */
    function savePassword() {
        let password = $("#password").val();
        if (password === ''){
            layer.msg('请输入密码', {icon: 2, time: 1000});
            return false;
        }
        let pwd = $("#pwd").val();
        if (pwd === ''){
            layer.msg('请输入确认密码', {icon: 2, time: 1000});
            return false;
        }
        if (pwd !== password){
            layer.msg('两次密码不一致', {icon: 2, time: 1000});
            return false;
        }

        $.ajax({
            url:'/api/savePassword',
            data: {"password":password},
            type:"post",
            dataType:'json',
            success:function(result){
                if (result.code === 200){
                    sessionStorage.removeItem("currentUser");
                    // 设置cookie
                    layer.msg(result.msg, {icon:1, time:1000}, function () {
                        location.href = '/login';
                    });
                }else {
                    layer.msg(result.msg, {icon:2});
                }
            }
        });
    }
</script>

<script>
    /**
     * 添加生日
     */
    function addBirthday() {
        layer.open({
            closeBtn: 1,
            type: 1,
            title:'添加生日',
            btn:['保存', '关闭'],
            area: ['90%', '500'],
            btnAlign: 'c',
            content: $("#add-form"),
            yes: function () {
                saveBirthday();
            },
            btn2: function (index) {
                layer.close(index);
            }
        })
    }

    function showDlt() {
        // 定义变量
        let redBall = []; // 红球
        let blueBall = []; // 蓝球

        // 生成红球
        for (let i = 1; i <= 35; i++) {
            redBall.push(i);
        }

        // 生成蓝球
        for (let i = 1; i <= 12; i++) {
            blueBall.push(i);
        }

        // 随机抽取红球
        let drawRedBall = [];
        for (let i = 0; i < 5; i++) {
            let randomIndex = Math.floor(Math.random() * redBall.length);
            drawRedBall.push(redBall[randomIndex]);
            redBall.splice(randomIndex, 1);
        }

        // 随机抽取蓝球
        let drawBlueBall = [];
        for (let i = 0; i < 2; i++) {
            let randomIndex = Math.floor(Math.random() * blueBall.length);
            drawBlueBall.push(blueBall[randomIndex]);
            blueBall.splice(randomIndex, 1);
        }

        // 将抽取的红蓝球排序
        drawRedBall = drawRedBall.sort((a, b) => a - b);
        drawBlueBall = drawBlueBall.sort((a, b) => a - b);
        let con = '红球：'+drawRedBall+'<br/>篮球：'+drawBlueBall;
        layer.open({
            closeBtn: 1,
            type: 1,
            title:'大乐透',
            btn:['确定'],
            area: ['90%', '500'],
            btnAlign: 'c',
            content: con,
            yes: function (index) {
                layer.close(index);
            },
        })
    }

    var form;
    /**
     * 保存生日
     * @returns {boolean}
     */
    function saveBirthday() {
        let data = form.val('add-form');

        let remark = data['remark'];
        if (remark === ''){
            layer.msg('请输入备注', {icon: 2, time: 1000});
            return false;
        }
        let type = data['type'];
        if (type === '1'){
            // 农历
            data['type'] = '2'
        }else {
            // 新历
            data['type'] = '1'
        }
        let birthday = data['birthday'];
        if (birthday === ''){
            layer.msg('请选择生日', {icon: 2, time: 1000});
            return false;
        }
        $.ajax({
            url:'/api/saveBirthday',
            data: data,
            type:"post",
            dataType:'json',
            success:function(result){
                if (result.code === 200){
                    layer.msg(result.msg, {icon:1, time:1000}, function () {
                        layer.closeAll();
                    });
                }else {
                    layer.msg(result.msg, {icon:2});
                }
            }
        });
    }

    layui.use(['form', 'laydate'], function(){
        var $ = layui.$;
        form = layui.form;
        var laydate = layui.laydate;

        laydate.render({
            elem: '#birthday'
        });
    });
</script>

<script>
    // 头像上传功能
    document.getElementById('avatar-container').addEventListener('click', function() {
        document.getElementById('avatar-upload').click();
    });

    document.getElementById('avatar-upload').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // 检查文件类型
            if (!file.type.match('image.*')) {
                layer.msg('请选择图片文件！');
                return;
            }

            // 检查文件大小（限制为2MB）
            if (file.size > 2 * 1024 * 1024) {
                layer.msg('图片大小不能超过2MB！');
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                const avatarImage = document.getElementById('avatar-image');
                const avatarPlaceholder = document.getElementById('avatar-placeholder');

                // 显示图片，隐藏占位符
                avatarImage.src = e.target.result;
                avatarImage.style.display = 'block';
                avatarPlaceholder.style.display = 'none';

                // 显示成功提示
                let formData = new FormData();
                formData.append("file", file);
                $.ajax({
                    type: 'post',
                    url: "/api/savePhoto",
                    data: formData,
                    cache: false,
                    processData: false,
                    contentType: false,
                }).success(function (result) {
                    $("#avatar-container").html('<img id="avatar-image" src="'+result.data.photo+'" alt="用户头像" class="avatar">');
                    // $("#avatar-image").attr("src", result.data.photo);
                    sessionStorage.setItem("currentUser", JSON.stringify(result.data));
                }).error(function () {
                    layer.msg("头像修改失败", {icon: 2});
                });
            };
            reader.readAsDataURL(file);
        }
    });

    // 菜单按钮交互效果
    // document.querySelectorAll('.menu-button').forEach(button => {
    //     button.addEventListener('click', function() {
    //         const buttonText = this.querySelector('.menu-text').textContent;
    //         alert(`您点击了: ${buttonText}`);
    //     });
    // });
</script>
</body>
</html>